from lxml import etree
text = '''
<div>
<ul>
<li class = "item-0"><a href = "link1.html">first item</a></li>
<li class = "item-1"><a href = "link2.html">second item</a></li>
<li class = "item-inactive"><a href = "link3.html">third item</a></li>
<li class = "item-1"><a href = "link4.html">fourth item</a></li>
<li class = "item-0"><a href = "link5.html">fif item</a>
</ul>
</div>
'''
# 按序选择
html = etree.HTML(text)
result = html.xpath('//li[1]/a/text()')
print(result)
result = html.xpath('//li[last()]/a/text()')
print(result)
result = html.xpath('//li[position()<3]/a/text()')
print(result)
result = html.xpath('//li[last()-2]/a/text()')
print(result)
text = '''
<div>
<ul>
<li class = "item-0"><a href = "link1.html"><span>first item</span></a></li>
<li class = "item-1"><a href = "link2.html">second item</a></li>
<li class = "item-inactive"><a href = "link3.html">third item</a></li>
<li class = "item-1"><a href = "link4.html">fourth item</a></li>
<li class = "item-0"><a href = "link5.html">fif item</a>
</ul>
</div>
'''
# 节点轴选择
html = etree.HTML(text)
result = html.xpath('//li[1]/ancestor::*')#调用ancestor轴，可以获取祖先节点，*代表所有
print(result)
result = html.xpath('//li[1]/ancestor::div')
print(result)
result = html.xpath('//li[1]/attribute::*')#调用attribute轴，获取属性值，*代表li节点的所有属性值
print(result)
result = html.xpath('//li[1]/child::a[@href="link1.html"]')#child轴，获取直接子节点
print(result)
result = html.xpath('//li[1]/descendant::span')#调用descendant轴，获取所有子孙节点
print(result)
result = html.xpath('//li[1]/following::*[2]')#调用following轴，获取当前节点之后的所有节点，*之后又加了下标索引，选取第二个节点
print(result)
result = html.xpath('//li[1]/following-sibling::*')#获取当前节点之后的所有同级节点
print(result)